package  
{
	import Common.GameDefine;
	import Common.GameNetManager;
	import Common.RenderManager;
	
	import battle.BattleCreature;
	
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import flash.utils.getTimer;
	
	import Common.MapDirection;
	import map.MapGrid;
	import map.MapPos;
	
	import net.NetHandler;
	
	import ui.ChatUIHandler;
	import ui.MapUIHandler;
	import ui.RoleInfoUIHandler;
	import ui.TopUIHandler;
	import Common.GameAction;
	
	/**
	 * ...
	 * @author ...
	 */
	public class GameManager 
	{
		private var mainPlayer:GamePlayer = null;
		
		// 30 turn / 1 second
		private var updateTimer:Timer = null;
		private var lastTime:Number = 0.0;
		private var nowTime:Number = 0.0;
		
		public var delay:Number = 0.0;
		public var delayCount:Number = 0.0;
		
		
		public function GameManager()
		{
			
		}
		
		public function init():void
		{
			updateTimer = new Timer( 30 );
			updateTimer.addEventListener( TimerEvent.TIMER , gameRun );
			
			updateTimer.stop();
			lastTime = getTimer();
			
			
		}
		
		
		private function onFrame( e:Event ):void
		{
			SceneManager.instance.render();
		}
		
		
		public function Run():void
		{
			updateTimer.start();
			
			RenderManager.instance.stage.addEventListener( Event.ENTER_FRAME , onFrame );
		}
		
		
		private function gameRun( e:TimerEvent ):void
		{
			nowTime = getTimer();
			
			delay = nowTime - lastTime;
			delayCount += delay;
			
			// logic run
			
			SceneManager.instance.update( delay );
			
			// render
			
			lastTime = nowTime;
			
			if ( delayCount > 100000 )
			{
				delayCount = 0;
				
				var date:Date = new Date();
				
				if ( TopUIHandler.instance )
					TopUIHandler.instance.setTime( date.hours , date.minutes );
				date = null;
			}
		}
		
		
		public function setMainPlayer( p:GamePlayer ):void
		{
			mainPlayer = p;
		}
		
		
		public function release():void
		{
			mainPlayer = null;
			updateTimer.stop();
			updateTimer = null;
		}
		
		
		public static var instance:GameManager = null;
		public static function Instance():GameManager
		{
			if ( instance == null )
			{
				instance = new GameManager();
			}
			
			return instance;
		}
		
		
		public function get MainPlayer():GamePlayer
		{
			return mainPlayer;
		}
		
		
		public function endFight():void
		{
			mainPlayer.setAction( GameAction.STAND  );
			mainPlayer.state = GameCeatureState.STAND;
			SceneManager.instance.Fight( false );
			
		}
		
		////////////////////////////////////////////////////////////////////////////////////
		
		
		
		
		
		
	}
	
}